package com.hotel.user.mapper;

import com.hotel.common.entity.User;
import com.hotel.common.utils.DBTools;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Repository
public class UserMapper {

    public User findById(Long id) {
        String sql = "SELECT id, username, password_bcrypt, real_name, tel, status, created_at, updated_at FROM user WHERE id = ?";
        List<Map<String, String>> result = DBTools.query(sql, id);
        if (result.isEmpty()) {
            return null;
        }
        return mapToUser(result.get(0));
    }

    public User findByUsername(String username) {
        String sql = "SELECT id, username, password_bcrypt, real_name, tel, status, created_at, updated_at FROM user WHERE username = ?";
        List<Map<String, String>> result = DBTools.query(sql, username);
        if (result.isEmpty()) {
            return null;
        }
        return mapToUser(result.get(0));
    }

    public List<User> findAll() {
        String sql = "SELECT id, username, password_bcrypt, real_name, tel, status, created_at, updated_at FROM user ORDER BY created_at DESC";
        List<Map<String, String>> result = DBTools.query(sql);
        return result.stream().map(this::mapToUser).collect(Collectors.toList());
    }

    public Long insert(User user) {
        String sql = "INSERT INTO user (username, password_bcrypt, real_name, tel, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)";
        LocalDateTime now = LocalDateTime.now();
        DBTools.update(sql, 
            user.getUsername(), 
            user.getPasswordBcrypt(), 
            user.getRealName(), 
            user.getTel(), 
            user.getStatus() != null ? user.getStatus() : 1,
            now,
            now
        );
        // 获取插入的主键
        return Long.valueOf(DBTools.querySingle("SELECT LAST_INSERT_ID()"));
    }

    public int update(User user) {
        String sql = "UPDATE user SET username = ?, real_name = ?, tel = ?, status = ?, updated_at = ? WHERE id = ?";
        return DBTools.update(sql, 
            user.getUsername(), 
            user.getRealName(), 
            user.getTel(), 
            user.getStatus(), 
            LocalDateTime.now(),
            user.getId()
        );
    }

    public int deleteById(Long id) {
        String sql = "DELETE FROM user WHERE id = ?";
        return DBTools.update(sql, id);
    }

    public int updatePassword(Long id, String passwordBcrypt) {
        String sql = "UPDATE user SET password_bcrypt = ?, updated_at = ? WHERE id = ?";
        return DBTools.update(sql, passwordBcrypt, LocalDateTime.now(), id);
    }

    public List<User> findByRoleId(Long roleId) {
        String sql = "SELECT u.id, u.username, u.password_bcrypt, u.real_name, u.tel, u.status, u.created_at, u.updated_at " +
                    "FROM user u INNER JOIN user_role ur ON u.id = ur.user_id WHERE ur.role_id = ?";
        List<Map<String, String>> result = DBTools.query(sql, roleId);
        return result.stream().map(this::mapToUser).collect(Collectors.toList());
    }

    private User mapToUser(Map<String, String> map) {
        return User.builder()
                .id(Long.valueOf(map.get("id")))
                .username(map.get("username"))
                .passwordBcrypt(map.get("password_bcrypt"))
                .realName(map.get("real_name"))
                .tel(map.get("tel"))
                .status(Integer.valueOf(map.get("status")))
                .createdAt(LocalDateTime.parse(map.get("created_at").replace(" ", "T")))
                .updatedAt(LocalDateTime.parse(map.get("updated_at").replace(" ", "T")))
                .build();
    }
}